<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>设备控制</title>
<link href="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/device.operator.css">
<script src="../scripts/jquery-3.4.0.min.js"></script>
<script src="../scripts/moment.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
</head>
<body>
  <?php require($_SERVER['DOCUMENT_ROOT'].'/common/header.html'); ?>
  <div class="container" style="width: 80%">
    <h1 style="margin-left: 20px">设备控制</h1>
    <br> 
    <div id="app">
      <template v-for="item in device.switch">       
        <div class="col-md-4"  id="mainid">
          <div class="panel panel-primary">
            <div class="panel-heading">
              <h3 class="panel-title">{{item.name}}</h3>
            </div>
            <div class="panel-body">
              <button type="button" :id="item.moduleid" class="operatorbtn green" value="1">打开</button>
              <button type="button" :id="item.moduleid" class="operatorbtn red" value="0">关闭</button>
              <p class="led led_off" :id="'state'+item.moduleid">OFF</p>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
<script src="/scripts/mqttws31.js"></script>
<script>
  var user;
  // 开关列表
  var device;
  var _deviceid = getUrlParam('deviceid');
  // 显示正在加载动画
  var loading = layer.load(0);
  /**********************获取用户登陆信息**************************************/
  $.ajax({
    url: "/api/user/user.php",
    async: false, //同步
    success: function (res) {
      user = res;
      new Vue({
        el: '#header1',
        data: {
          user: user
        }
      })
      //关闭加载动画
      layer.close(loading); 
    },
    error:function (res) {
        console.log('fail:',res);
    }
  });

  if (user.login=='false') {
     //公告层
      layer.open({
        type: 1
        ,title: false //不显示标题栏
        ,closeBtn: false
        ,area: '300px;'
        ,shade: 0.8
        ,id: 'LAY_layuipro' //设定一个id，防止重复弹出
        ,btn: ['前去登陆', '看看再说']
        ,btnAlign: 'c'
        ,moveType: 1 //拖拽模式，0或者1
        ,content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 400;">亲,进入设备控制需要登陆哦！</div>'
        ,success: function(layero){
          var btn = layero.find('.layui-layer-btn');
          btn.find('.layui-layer-btn0').attr({
            href: '/user/login.php'
            ,target: '_blank'
          });
          btn.find('.layui-layer-btn1').attr({
            href: '/index.php'
          });
        }
      });
    }
    else
    {
      $.ajax({
        type:'POST',
        async: false, //同步
        url: "/api/device/device.getdevice.php",
        data:{userid:user.userid,deviceid:_deviceid},
        success: function (res) {
          device  = res;

          if (device.module_count==0) {
            layer.alert('您还没有添加模块！');
          }
          else
          {
             new Vue({
              el: '#app',
              data: {
                device: device
              }
            })
          }
          console.log('device.getdevice.list:[Ok]',res);
        },
        error:function (res) {
          device = null;
          layer.alert('API地址无效！')
          console.log('device.getdevice.list:[Fail]',res);
        }
      });
    }
    /**********************MQTT**************************************/
    var client;
    var operator_id = (new Date()).valueOf(); //ms时间戳，唯一话题标志
    var connect_clientId = (new Date()).valueOf().toString();
    $(function() {
      var host = '47.102.150.235';    
      var port = '61623';
      var clientId = connect_clientId;
      var user = 'admin';
      var password = 'password';
      client = new Messaging.Client(host, Number(port), clientId);
      client.onConnect = onConnect;
      client.onMessageArrived = onMessageArrived;
      client.onConnectionLost = onConnectionLost;            

      client.connect({
        userName:user, 
        password:password, 
        onSuccess:onConnect, 
        onFailure:onFailure
      }); 
      return false;
    });  

    // the client is notified when it is connected to the server.
    var onConnect = function(frame) {
      console.log("connected to MQTT");
      client.subscribe('device-'+_deviceid+"/feedback");
      //查询设备状态
    var obj={
      "id":Math.floor(Math.random()* 100000).toString(), 
      "messageType": "get",  
      "moduleType": "switch" 
    }
    str = JSON.stringify(obj);
    console.log("查询设备状态：",str);
    publish('device-'+_deviceid+"/get",str);
  };  
  function onFailure(failure) {
    console.log("failure");
    console.log(failure.errorMessage);
  }  

  function onMessageArrived(message) {
    var obj = JSON.parse(message.payloadString);
    console.log('收到订阅话题：device-'+_deviceid+"/feedback:",obj);
    //打开和关闭后更新状态
    for (var index = 0; index < obj.data.length; index++) {
      if(obj.data[index].value==0)
      {
        // console.log('off:',"#state"+(index+1).toString());
        $("#state"+(index+1).toString()).removeClass("led led_on led_off");
        $("#state"+(index+1).toString()).addClass("led led_off");
        $("#state"+(index+1).toString()).text("OFF");
      }
      else
      {
        // console.log('on:',"#state"+(index+1).toString());
        $("#state"+(index+1).toString()).removeClass("led led_on led_off");
        $("#state"+(index+1).toString()).addClass("led led_on");
        $("#state"+(index+1).toString()).text("ON");
      }
    }
  }

  function onConnectionLost(responseObject) {
    if (responseObject.errorCode !== 0) {
      console.log(client.clientId + ": " + responseObject.errorCode + "\n");
    }
  }

  function publish(topic,text) {
    if (text) {
      message = new Messaging.Message(text);
      message.destinationName = topic;
      client.send(message);
    }
    return false;
  }

  //button引起的变化
  $(":button").bind("click",function(){
    //打印引起事件的标签信息
    console.log('click:', this);
    var moduleid = $(this).attr('id');
    var value = $(this).attr('value');
    console.log('moduleid:', moduleid);
    operator_id = (new Date()).valueOf(); //ms时间戳，唯一话题标志
    // 发布控制话题
    var str='{"id":"'+operator_id.toString()+'","messageType":"control","deviceType": "switch","num":1,"data":[{"moduleid":'+moduleid+',"value":'+value+'}]}';
    publish('device-'+_deviceid+"/control",str);
    console.log('发布控制话题：device-'+_deviceid+"/control",str);
    //模拟传感器返回
    // var str='{"messageType":"feedback","deviceType": "switch","resault":1,"num":1,"data":[{"moduleid":'+moduleid+',"value":'+value+'}]}';
    // publish('device-'+_deviceid+"/feedback",str);
    // console.log('模拟发布反馈话题：device-'+_deviceid+"/feedback",str);

  });
</script>
<?php include $_SERVER ['DOCUMENT_ROOT']."/common/footer.php";?>
</body>
</html>